# -*- coding: utf-8 -*-
############################################################################
from chee.shortcuts import *
from chee.models import User_Info
############################################################################
class Static(StaticHandler):
    rule = Rule('/static/<path:path>')
    static_dir = os.path.join(base_path, 'static')
class RootStatic(StaticHandler):
    rule = Rule('/<path:path>')
    static_dir = os.path.join(base_path, 'root_static')
class Json_Page_Test(AuthHandler):
    rule = Rule('/test/json/')
    def get(self):
        tmpl = env.get_template('test.html')
        return Response(tmpl.render(request = self.request, errors = self.errors))
class Single_Image_Upload(AuthHandler):
    rule = Rule('/simgup/')
    def get(self):
        err = self.request.args.get('err','').strip()
        import base64
        if err: self.errors['up_file'] = err
        tmpl = env.get_template('tool/simgup.html')
        return Response(tmpl.render(request = self.request, errors = self.errors))
class Login(AuthHandler):
    rule = Rule('/login/')
    _redirect_url = ''
    def get(self):
        to = self.request.args.get('to','').strip()
        page = 'user/login.html'
        if self.request.user: page = 'user/logged.html'
        tmpl = env.get_template(page)
        return Response(tmpl.render(
            request = self.request, errors = self.errors,
            _redirect_url = self._redirect_url, to = to, main_active = "myspace"
        ))
    def post(self):
        try:
            username = self.request.form.get('username', u'').strip()
            password = self.request.form.get('password', u'').strip()
            user = store.find(User_Info, User_Info.name==username).one()
            if user:
                if user.checkPassword(password):
                    user.login(self.request)
                    redirect_url = self.request.form.get('to', '/')
                    response = redirect(redirect_url)
                    response.set_cookie('un',username,expires=datetime.now()+timedelta(365))
                    uik = user.key
                    response.set_cookie('uid',str(user.id))
                    response.set_cookie('uik',uik)
                    self._redirect_url = '/'
                    return response
                else:
                    self.errors['login'] = u'密码校验错误'
            else:
                self.errors['login'] = u'用户不存在'
        except: self.errors['login'] = u'用户检测错误，请联系管理员'
        self._redirect_url = self.request.form.get('to', '/')
        return self.get()
class Login_Ajax(AuthHandler):
    rule = Rule('/alogin/')
    def post(self):
        try:
            username = self.request.form.get('username', u'').strip()
            password = self.request.form.get('password', u'').strip()
            user = store.find(User_Info, User_Info.name==username).one()
            if user:
                if user.checkPassword(password):
                    user.login(self.request)
                    resp = Response(encodeJsonMsg(True,u''))
                    resp.set_cookie('un',username, expires=datetime.now()+timedelta(365))
                    uik = user.key
                    resp.set_cookie('uid',str(user.id))
                    resp.set_cookie('uik',uik)
                    resp.set_cookie('unick',user.nick_name)
                    return resp
                else:
                    return Response(encodeJsonMsg(False,u'密码校验错误'))
            else:
                return Response(encodeJsonMsg(False,u'用户不存在'))
        except:
            return Response(encodeJsonMsg(False,u'用户检测错误，请联系管理员'))
class Logout(AuthHandler):
    rule = Rule('/logout/')
    def get(self):
        to = '/'
        to = self.request.args.get('to','').strip()
        if not to: to = self.request.net_loc
        else: to = to.replace('/%s/'%self.request.host,'/%s/'%self.request.net_loc)
        logout(self.request)
        # delete cookies
        resp = redirect(to)
        resp = doLogout(self.request,resp)
        return resp
class Register(AuthHandler):
    rule = Rule('/reg/')
    def get(self):
        to = self.request.args.get('to','/').strip()
        page = 'user/reg.html'
        if self.request.user_id: page = 'user/logged.html'
        tmpl = env.get_template(page)
        return Response(tmpl.render(
            request = self.request, errors = self.errors, to = to, main_active = "myspace"
        ))
    def post(self):
        name = self.request.form.get('username', u'').strip()
        password = self.request.form.get('password', u'').strip()
        nick = self.request.form.get('nickname', u'').strip()
        name = toHtml(name); nick = toHtml(nick) 
        if not name: return Response(encodeJsonMsg(False,u'用户名不能为空'))
        else:
            has = User_Info.hasUser(name)
            if has: return Response(encodeJsonMsg(False,u'用户名已经被注册'))
        if password == '':
            return Response(encodeJsonMsg(False,u'密码不能为空'))
        if nick == '':
            return Response(encodeJsonMsg(False,u'昵称不能为空'))
        
        usrid = User_Info.addNew(usrname=name,nick_name=nick,email=name,request=self.request,usr_photo=u'',password=password)
        # send user an inner mail
        title = u'欢迎加入!'
        content = u'亲爱的%s：<br />欢迎你加入! 数千部精彩的在线高清视频期待您的欣赏，随时随地，随心点播！' % nick
        sendSysMail(usrid,title,content)
        return Response(encodeJsonMsg(True,''))
class RegSuccess(AuthHandler):
    rule = Rule('/reg_success/')
    def get(self):
        page = 'user/reg_success.html'
        tmpl = env.get_template(page)
        return Response(tmpl.render(
            request = self.request, errors = self.errors, main_active = u"myspace"
        ))
class RegLicense(AuthHandler):
    rule = Rule('/reg/lic/')
    def get(self):
        page = 'user/reg_license.html'
        tmpl = env.get_template(page)
        return Response(tmpl.render(
            request = self.request, errors = self.errors, main_active = u"myspace"
        ))
class RegUtils(AuthHandler):
    rule = Rule('/reg/utils/')
    def post(self):
        try:
            req_type = self.request.form.get('type','').strip()
            s = ""
            if req_type == u"accexist":
                usr_name = self.request.form.get('value',u'').strip()
                if User_Info.hasUser(usr_name): s = encodeJsonMsg(False,u'该邮箱地址已经被注册')
                else: s = encodeJsonMsg(True,'')
            elif req_type == u"nickexist":
                n_name = self.request.form.get('value',u'').strip()
                count = User_Info.hasNickCount(n_name)
                s = encodeJsonMsg(True,count)
            return Response(s)
        except: return Response(encodeJsonMsg(False,u'暂时无法连接网络，请您稍后再试。'))
if __name__ == '__main__':
    print ''
    
